<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>

        <el-button v-if="isAuth('hotel:thotelcashbillsproject:save')" type="primary" @click="posAddOrUpdateHandle()">POS管理</el-button>
        <el-button v-if="isAuth('hotel:thotelcashbills:save')" type="primary" @click="addOrUpdateHandle()">添加POS消费</el-button>

      </el-form-item>

      <el-form-item>
        <el-select @change="getDataList" v-model="dataForm.projectId" placeholder="请选择">
          <el-option label="全部" :value="''"></el-option>
          <el-option v-for="item in projectList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select @change="getDataList" v-model="dataForm.state" placeholder="请选择">
          <el-option label="全部" :value="''"></el-option>
          <el-option v-for="item in stateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" @change="dateSelectHandel" v-model="value2" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" align="right">
        </el-date-picker>
      </el-form-item>

    </el-form>
    <el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 100%;"
      :default-sort="{prop: 'date', order: 'descending'}">

      <el-table-column prop="billNo" width="200" header-align="center" align="center" label="单据号" sortable :show-overflow-tooltip="true">
      </el-table-column>

      <el-table-column prop="projectId" header-align="center" align="center" label="消费点" sortable>
        <template slot-scope="scope">

          <el-tag type="warning"> {{projects[scope.$index].name}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="courseInfo" header-align="center" align="center" label="消费信息">
      </el-table-column>

      <el-table-column prop="type" header-align="center" align="center" label="挂房账">
        <template slot-scope="scope">
          <el-tag>{{scope.row.type==1?'是':'否'}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="peopleId" header-align="center" align="center" label="挂账人">
        <template slot-scope="scope">
          {{scope.row.type==1?rooms[scope.$index].roomSign+rooms[scope.$index].roomNum+"-"+peoples[scope.$index].name:"无"}}
        </template>
      </el-table-column>

      <el-table-column prop="consumeMoney" header-align="center" align="center" label="消费金额" sortable>
      </el-table-column>

      <el-table-column prop="discountPrice" header-align="center" align="center" label="优惠金额" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.discountPrice">{{scope.row.discountPrice}}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>


      <el-table-column prop="payMoneyInfo" header-align="center" align="center" label="付款">
        <template slot-scope="scope">
          <span v-if="scope.row.payMoneyInfo">{{scope.row.payMoneyInfo}}</span>
          <span v-else>无</span>
        </template>
      </el-table-column>

      <el-table-column prop="note" header-align="center" align="center" label="备注">
        <template slot-scope="scope">
          {{scope.row.note ? scope.row.note : '无'}}
        </template>
      </el-table-column>

      <el-table-column prop="createTime" header-align="center" align="center" label="创建时间" sortable>
      </el-table-column>


      <el-table-column prop="state" header-align="center" align="center" label="状态" sortable>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type == 0" :type="stateMap[scope.row.state]">
            {{scope.row.state==1?'已结账':'未结账'}}
          </el-tag>
          <el-tag v-else :type="stateMap[scope.row.state]">
            {{scope.row.state==1?'已挂账':'未挂账'}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="revoke(scope.row.id)" v-if="scope.row.state ==1 && scope.row.shiftWorkId == null">撤销</el-button>
          <el-button type="text" size="small" @click="printHandle(scope.row.id)" v-if="scope.row.state ==1">打印</el-button>
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)" v-if="scope.row.state==0">修改</el-button>
          <el-button type="text" size="small" @click="checkOutBillsHandle(scope.row.id)" v-if="scope.row.state==0 && scope.row.type== 0">结账</el-button>
          <el-button type="text" size="small" v-if="scope.row.state == 0 " @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <posAddOrUpdate v-if="posAddOrUpdateVisible" ref="posAddOrUpdate" @refreshDataList="getDataList"></posAddOrUpdate>

    <CheckOutBills v-if="checkOutBillsVisible" ref="checkOutBills" @refreshDataList="getDataList"></CheckOutBills>

    <pos58 v-show="false" id="pos58" ref="pos58"></pos58>
    <pos80 v-show="false" id="pos80" ref="pos80"></pos80>
    <posA5 v-show="false" id="posA5" ref="posA5"></posA5>
  </div>
</template>

<script>
  import pos58 from '../../../common/printtemplate/pos_58mm';
  import pos80 from '../../../common/printtemplate/pos_80mm';
  import posA5 from '../../../common/printtemplate/pos_A5';
  import AddOrUpdate from './thotelcashbills-add-or-update'
  import PosAddOrUpdate from './project/thotelcashbillsproject'
  import CheckOutBills from './check-out-bills'
  import {
    getLodop
  } from '../../../../utils/lodop';
  export default {
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value2: [],
        dataForm: {
          key: '',
          projectId: '',
          state: '',
        },
        stateList: [{
            id: 0,
            name: '未结账'
          },
          {
            id: 1,
            name: '已结账'
          },
        ],
        projectList: [],
        dataList: [],
        peoples: [],
        rooms: [],
        printconfig: {},
        payTypes: [],
        projects: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        checkOutBillsVisible: false,
        dataListSelections: [],
        posAddOrUpdateVisible: false,
        addOrUpdateVisible: false,
        startTime: '',
        stopTime: '',
        stateMap: ['danger', 'success']
      }
    },
    components: {
      AddOrUpdate,
      PosAddOrUpdate,
      CheckOutBills,
      pos80,
      pos58,
      posA5
    },
    activated() {
      this.getDataList()
      this.loadPrintConfig();
      this.loadTabs();
    },
    methods: {
      dateSelectHandel(val){
        console.log(val)
        this.getDataList();
      },
      loadTabs() {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelcashbillsproject/listByState'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 999,
            'state': 1
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.projectList = data.page.list
          } else {
            this.projectList = []
          }
        })
      },
      checkOutBillsHandle(id) {
        this.checkOutBillsVisible = true
        this.$nextTick(() => {
          this.$refs.checkOutBills.init(id)
        })
      },
      loadPrintConfig() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelprinttemplate/info/10`),
          method: 'get'
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.printconfig = data.tHotelPrintTemplate;
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelcashbills/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            ...this.dataForm,
            'startStopTime': this.value2 ? this.value2.join(",") : '',
          })
        }).then(({
          data
        }) => {
          console.log("现付账:", data)
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
            this.peoples = data.peoples
            this.rooms = data.rooms
            this.payTypes = data.payTypes
            this.projects = data.projects
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // POS管理
      posAddOrUpdateHandle() {
        this.posAddOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.posAddOrUpdate.init()
        })
      },
      revoke(id) {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelcashbills/revoke/' + id),
          method: 'get'
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '撤销成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      printHandle(id) {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelcashbills/print/' + id),
          method: 'get'
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            var pdata = data.data
            this.$refs.pos58.initData(pdata);
            this.$refs.pos80.initData(pdata);
            this.$refs.posA5.initData(pdata);
            console.log(pdata);

            this.$message({
              message: '正在执行打印',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.printPos();
              }
            });
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      printPos() {
        this.$nextTick(() => {
          setTimeout(() => {
            LODOP = getLodop();
            if (!LODOP) {
              this.$alert(
                `<br><font color='#FF00FF'>CLodop云打印服务(localhost本地)未安装启动!点击这里<a href='http://www.lodop.net/download/CLodop_Setup_for_Win32NT_4.088Extend.zip' download target='_blank'>执行安装</a>,安装后请刷新页面。</font>`,
                '安装', {
                  confirmButtonText: '确定',
                  dangerouslyUseHTMLString: true
                }
              );
              return;
            }

            //样式
            var strStyleCSS =
              " <link href='https://ebooking.qlan99.com/css/print.css' type='text/css' rel='stylesheet'> ";

            var olstyle1 = '<!DOCTYPE html><html lang="zh-CN"><head>' + strStyleCSS + '</head>' + ' <style> ' +
              'div{border:0!important}' + '</style>';
            var body = '';
            if (this.printconfig.specs === '58mm') {
              var olstyle2 = '<style> .print-wrap-normal{width:' + (58 + parseInt(this.printconfig.printContentOffset)) +
                'mm  !important}</style>';
              body = olstyle1 + olstyle2 + '<body>' + this.$refs.pos58.$refs.pos58.innerHTML + '</body>';
              LODOP.SET_PRINT_PAGESIZE(0, 580, 3000, ''); //设定纸张大小
            }
            if (this.printconfig.specs === '80mm') {
              var olstyle2 = '<style> .print-wrap-normal{width:' + (80 + parseInt(this.printconfig.printContentOffset)) +
                'mm  !important}</style>';
              body = olstyle1 + olstyle2 + '<body>' + this.$refs.pos80.$refs.pos80.innerHTML + '</body>';
              LODOP.SET_PRINT_PAGESIZE(0, 800, 2500, ''); //设定纸张大小
            }
            if (this.printconfig.specs === 'A5') {
              var olstyle2 = '<style> .print-wrap-normal{width:' + (210 + parseInt(this.printconfig.printContentOffset)) +
                'mm  !important}</style>';
              body = olstyle1 + olstyle2 + '<body>' + this.$refs.posA5.$refs.posA5.innerHTML + '</body>';
              LODOP.SET_PRINT_PAGESIZE(0, 2100, 2000, ''); //设定纸张大小
            }
            body += '</html>';
            LODOP.ADD_PRINT_HTM(0, 0, 1000, 2000, body); //增加超文本项

            LODOP.SET_PRINT_MODE('PRINT_PAGE_PERCENT', '100%'); //设置缩放
            // LODOP.PRINT_INIT('订单') //打印初始化
            LODOP.SET_PRINT_STYLE('FontSize', 12); //设置对象风格
            LODOP.SET_PRINT_STYLE('Bold', 1); ////设置对象风格
            LODOP.SET_PREVIEW_WINDOW(0, 0, 0, 0, 0, ''); //设置窗口
            LODOP.SET_PRINT_COPIES(this.printconfig.printSum);

            LODOP.SET_LICENSES("", "4B44F795076C8F14211A5ED0A5339305DAB", "23580B189D96F33252722697A57AC00506B",
              "");

            if (this.printconfig.preview) {
              if (LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint)) {
                LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint);
                LODOP.PRINT();
                // LODOP.PRINT_DESIGN();
              } else {
                LODOP.SET_PRINTER_INDEXA(0);
                LODOP.PRINT();
                // LODOP.PRINT_DESIGN();
              }
            } else {
              if (LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint)) {
                LODOP.SET_PRINTER_INDEXA(this.printconfig.defaultPrint);
                LODOP.PREVIEW();
              } else {
                LODOP.SET_PRINTER_INDEXA(0);
                LODOP.PREVIEW();
                // LODOP.PRINT_DESIGN();
              }
            }
          }, 100)

        });
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/hotel/thotelcashbills/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
  }
</script>
